/* eslint-disable @typescript-eslint/no-explicit-any */
// 封装独立的 axios 库,方便 axios 不维护切换其他的库
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import type { AxiosInstance } from 'axios'
import { AxiosRequestConfigWithInterceptor } from './types'
import QS from 'qs'
import { ElLoading } from 'element-plus'
class Request {
  private instance: AxiosInstance // axios 实例
  private LodgingInstance: any
  constructor(config: AxiosRequestConfigWithInterceptor) {
    this.instance = axios.create(config)
    // 组件级拦截器
    this.instance.interceptors.request.use(
      config.interceptors?.request,
      config.interceptors?.requestErr
    )
    this.instance.interceptors.response.use(
      config.interceptors?.response,
      config.interceptors?.responseErr
    )
    //全局拦截器
    this.instance.interceptors.request.use(
      this.globalReqInterceptors.bind(this),
      this.globalReqInterceptorsErr.bind(this)
    )
    this.instance.interceptors.response.use(
      this.globalRespInterceptors.bind(this),
      this.globalRespInterceptorsErr.bind(this)
    )
  }
  globalReqInterceptors(config: AxiosRequestConfig) {
    this.LodgingInstance = ElLoading.service({
      lock: true,
      background: 'rgba(0,0,0,.3)',
      text: '拼命加载中'
    })

    return config
  }
  globalReqInterceptorsErr(err: any) {
    return err
  }
  globalRespInterceptors(response: AxiosResponse) {
    this.LodgingInstance?.close()
    const data = response.data
    switch (data.returnCode) {
      case '-1001':
        console.log('请求失败')
        break
      default:
        return data
    }
  }
  globalRespInterceptorsErr(err: any) {
    this.LodgingInstance?.close()

    const code = err?.response?.status
    switch (code) {
      case '404':
        console.log('404错误')
        break
    }
    return err
  }

  // 封装方法
  get(url: string, params: any) {
    return new Promise((resolve, reject) => {
      this.instance
        .get(url, { params })
        .then((res) => resolve(res.data))
        .catch((err) => reject(err))
    })
  }
  post(url: string, data: any) {
    return new Promise((resolve, reject) => {
      this.instance
        .post(url, QS.stringify(data))
        .then((res) => resolve(res.data))
        .catch((err) => reject(err))
    })
  }
  delete(url: string, params: any) {
    return new Promise((resolve, reject) => {
      this.instance
        .delete(url, { params })
        .then((res) => resolve(res.data))
        .catch((err) => reject(err))
    })
  }
  patch(url: string, data: any) {
    return new Promise((resolve, reject) => {
      this.instance
        .patch(url, QS.stringify(data))
        .then((res) => resolve(res.data))
        .catch((err) => reject(err))
    })
  }
}

export default Request
